import numpy as np
from matplotlib import pyplot as plt
import os
import tensorflow as tf
from PIL import Image
from utils import label_map_util
from utils import visualization_utils as vis_util

import datetime
# 关闭tensorflow警告
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'

detection_graph = tf.Graph()

#---------model
pbfile='ssd_mobilenet_v1_coco_11_06_2017' + '/frozen_inference_graph.pb'
pbtxtPath='data'
pbtxtFile='mscoco_label_map.pbtxt'

#--------模型
# pbfile='E:/python-space/eci/objectDecision/test/ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb'
# pbtxtPath='E:/python-space/eci/objectDecision/test/ssd_mobilenet_v1_coco_11_06_2017'
# pbtxtFile='graph.pbtxt'


#------天线
# pbfile='E:/python-space/tool/result/frozen_inference_graph.pb'
# pbfile='E:/python-space/tool/testresult/frozen_inference_graph.pb'
pbfile='E:/python-space/tool/jietu_pb/frozen_inference_graph.pb'
# pbtxtPath='data'
pbtxtFile='jietu.pbtxt'



# 加载模型数据-------------------------------------------------------------------------------------------------------
def loading():
    with detection_graph.as_default():
        od_graph_def = tf.GraphDef()
        PATH_TO_CKPT = pbfile
        with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
            serialized_graph = fid.read()
            od_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(od_graph_def, name='')
    return detection_graph



def load_image_into_numpy_array(image):
    '''
    根据图片大小进行像素点切割
    '''
    (im_width, im_height) = image.size
    data =np.array(image.getdata())
    if data.shape[1]==4:  #如果图片深度为32，去除最后一列透明度
        data=np.delete(data,-1,axis=1);
    return data.reshape((im_height, im_width, 3)).astype(np.uint8)

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join(pbtxtPath, pbtxtFile)
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=90, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

def Detection(image_path="images/image1.jpg",partition=0.99,model=0):
    loading()
    with detection_graph.as_default():
        with tf.Session(graph=detection_graph) as sess:
            image = Image.open(image_path)

            # 获取np结构的图片像素点
            image_np = load_image_into_numpy_array(image)

            # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(image_np, axis=0)
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            
            # Each box represents a part of the image where a particular object was detected.
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

            # Each score represent how level of confidence for each of the objects.
            # Score is shown on the result image, together with the class label.
            scores = detection_graph.get_tensor_by_name('detection_scores:0')  #目标百分率
            classes = detection_graph.get_tensor_by_name('detection_classes:0') #类别
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

            #评估目标位置和类别
            (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})

            #概率过滤
            newScores=[]
            newBoxes=[]
            for i in range(5):
                if float(scores[0][i])>=float(partition):
                    newScores.append(scores[0][i])
                    newBoxes.append(boxes[0][i])
            
            scores=np.array([newScores])

            #目标图片概率值
            i=0
            for m in range(len(scores[0])):
                if classes[0][i] in category_index.keys():
                    class_name = category_index[classes[0][i]]['name']
                else:
                    class_name = 'N/A'
                print("物体：%s 概率：%s" % (class_name, scores[0][i]))
                i+=1
            
            if model != 0:
                return

            if len(newBoxes)==1:
                boxes=np.array(newBoxes)
                vis_util.visualize_boxes_and_labels_on_image_array(image_np,boxes,np.squeeze(classes).astype(np.int32),scores,
                category_index,use_normalized_coordinates=True,line_thickness=8,min_score_thresh=partition)
            else: 
                boxes=np.array([newBoxes])
                vis_util.visualize_boxes_and_labels_on_image_array(image_np,np.squeeze(boxes),np.squeeze(classes).astype(np.int32),np.squeeze(scores),
                category_index,use_normalized_coordinates=True,line_thickness=8,min_score_thresh=partition)
                
            # matplotlib输出图片
            IMAGE_SIZE = (20, 12)
            plt.figure(figsize=IMAGE_SIZE)
            plt.imshow(image_np)
            plt.show()

def findImage(path):
    '''
    加载文件
    '''
    import glob
    img_list = []
    for img_file in glob.glob(path + '/*.JPG'):
        img_list.append(img_file)
    return img_list


def saveFile(data,url='./true.txt'):
    '''
    数据保存为文件
    '''
    f=open(url,'a')
    print(data,file=f)
    f.close()

def main():
    url="images/huanxiong.jpg"
    # url="images/demo.jpg"
    # url="E:/python-space/eci/objectDecision/tianxian/image/train/IMG_5484.JPG"
    url="E:/python-space/eci/objectDecision/tianxian/image/train/IMG_5407.JPG"#有问题
    url="E:/python-space/eci/objectDecision/tianxian/image/train/IMG_5573.JPG"#有问题
    url="E:/python-space/eci/objectDecision/tianxian/image/train/IMG_5579.JPG"#有问题
    url="E:/python-space/eci/objectDecision/tianxian/image/train/IMG_5460.JPG"

    # url="E:/python-space/HW_ Antenna/OutputPics/DJI_003101.jpg"
    # url="E:/python-space/HW_ Antenna/OutputPics/DJI_003103.jpg"
    # url="E:/python-space/HW_ Antenna/OutputPics/DJI_003109.jpg"
    # url="E:/python-space/HW_ Antenna/OutputPics/DJI_003122.jpg"

    url="E:/python-space/HW_img_jieTu/train/DJI_1_19.jpg"
    Detection(url,0.20)
    
    
    # path="E:/python-space/eci/objectDecision/tianxian/image/train";
    # path="E:/python-space/HW_img_jieTu/test"
    # img_list=findImage(path)
    # for i in range(len(img_list)):
    #     print(img_list[i])
    #     Detection(img_list[i],partition=0.5,model=1)
    #     print("是否存储  1 正常  其他 异常")
    #     param=int(input())
    #     if param ==1:
    #         saveFile(img_list[i])
    #     else:
    #         saveFile(img_list[i],url="false.txt")


if __name__ == '__main__':
    main()